<?php


namespace App\Repositories;


use App\Mail\Manage\UserPasswordMail;
use App\Models\Customer as Model;
use App\Traits\Logs;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use LTools\Traits\CodeTrait;
use LTools\Repositories\RepositoryAbstract;

class Customer extends RepositoryAbstract
{
    use CodeTrait, Logs;

    /**
     * Customer constructor.
     * @param Model $model
     */
    public function __construct(Model $model)
    {
        $this->model = $model;
    }

    /**
     * @param array $attributes
     * @return bool|\Illuminate\Database\Eloquent\Model
     */
    public function create(array $attributes = [])
    {
        $attributes['code'] = $this->unique(4, "C");
        $model = parent::create($attributes);
        $this->recordLogs($model, '创建客户成功');
        return $model;
    }

    /**
     * @param $id
     * @param array $values
     * @return Model
     * @throws \Throwable
     */
    public function update($id, array $values)
    {
        /** @var Model $model */
        $model = $this->find($id);
        if ($model->canUpdate()) {
            $values['status'] = 0;
            $model->fillable(['code', 'name', 'status', 'license', 'remark'])->fill($values)->saveOrFail();
            $this->recordLogs($model, '客户修改成功');
            return $model;
        }
        throw new Exception("当前状态不能修改！");
    }

    /**
     * @param $id
     * @return Model
     */
    public function show($id)
    {
        /** @var Model $model */
        $model = $this->find($id);
        $model->load(['logs.user']);
        $user = $model->users()->whereNull('role_id')->first();
        $model->setAttribute('user', $user);
        return $model;
    }

    /**
     * @param $id
     * @param array $values
     * @return \Illuminate\Database\Eloquent\Model
     * @throws Exception
     */
    public function user($id, array $values)
    {
        /** @var Model $model */
        $model = $this->model->newQuery()->lockForUpdate()->find($id);
        if ($model->isNormal()) {
            if ($model->users()->count() === 0) {
                $values['password'] = Str::random(12);
                $values['status'] = 1;
                $user = $model->users()->create($values);

                Mail::to($user->getAttribute('email'))->queue(new UserPasswordMail($values));

                $this->recordLogs($model, '添加主账号成功');
                return $user;
            }
            throw new Exception("已有主账号不能添加");
        }
        throw new Exception("当前状态不能添加主账号！");
    }

    /**
     * @param $id
     * @return Model
     * @throws \Throwable
     */
    public function confirm($id)
    {
        /** @var Model $model */
        $model = $this->find($id);
        if ($model->canConfirm()) {
            $model->setAttribute('status', 1)->saveOrFail();
            $this->recordLogs($model, '客户确认成功');
            return $model;
        }
        throw new Exception("当前状态不能提交！");
    }

    /**
     * @param $id
     * @return Model
     * @throws \Throwable
     */
    public function examine($id)
    {
        /** @var Model $model */
        $model = $this->find($id);
        if ($model->canExamine()) {
            $model->setAttribute('status', 3)->saveOrFail();
            $this->recordLogs($model, '客户审核成功');
            return $model;
        }
        throw new Exception("当前状态不能审核！");
    }

    /**
     * @param $id
     * @return Model
     * @throws \Throwable
     */
    public function reject($id)
    {
        /** @var Model $model */
        $model = $this->find($id);
        if ($model->canReject()) {
            $model->setAttribute('status', 2)->saveOrFail();
            $this->recordLogs($model, '客户驳回成功:' . request()->input('reject'));
            return $model;
        }
        throw new Exception("当前状态不能驳回！");
    }

    /**
     * @param $id
     * @return Model
     * @throws \Throwable
     */
    public function frozen($id)
    {
        /** @var Model $model */
        $model = $this->find($id);
        if ($model->canFrozen()) {
            $model->setAttribute('status', 4)->saveOrFail();
            $this->recordLogs($model, '客户冻结成功');
            return $model;
        }
        throw new Exception("当前状态不能冻结！");
    }

    /**
     * @param $id
     * @return Model
     * @throws \Throwable
     */
    public function thaw($id)
    {
        /** @var Model $model */
        $model = $this->find($id);
        if ($model->canThaw()) {
            $model->setAttribute('status', 3)->saveOrFail();
            $this->recordLogs($model, '客户解冻成功');
            return $model;
        }
        throw new Exception("当前状态不能解冻！");
    }

    /**
     * @param $id
     * @return bool|mixed|void
     * @throws Exception
     */
    public function delete($id)
    {
        /** @var Model $model */
        $model = $this->find($id);
        if ($model->canDelete()) {
            $model->logs()->delete();
            $model->users()->delete();
            $model->delete();
            return true;
        }
        throw new Exception("当前状态不能删除！");
    }

    /**
     * @param $id
     * @throws Exception
     */
    public function password($id)
    {
        /** @var Model $model */
        $model = $this->find($id);
        /** @var \App\Models\CustomerUser $user */
        try {
            $user = $model->users()->whereNull('role_id')->firstOrFail();
            $values = [];
            $values['password'] = Str::random(12);
            $user->update($values);

            Mail::to($user->getAttribute('email'))->queue(new UserPasswordMail(
                array_merge($user->toArray(), $values)
            ));

            $this->recordLogs($model, '修改主账号密码成功');
        } catch (ModelNotFoundException $exception) {
            Log::error($exception);
            throw new Exception("没有找到对应的主账号！");
        } catch (\Throwable $e) {
            Log::error($e);
            throw new Exception("修改主账号密码失败！");
        }
    }

}
